package dshop.interceptor;

import java.util.Calendar;
import java.util.Date;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

import appbase.jfinal.ext.ApiBaseController;
import appbase.jwt.JWTKit;
import dshop.AppConst;
import io.jsonwebtoken.Claims;

public class AppUserAuthInterceptor implements Interceptor{

	@Override
	public void intercept(Invocation ai) 
	{
		//ai.invoke();
		
		Controller ctrl = ai.getController();
		String token = ctrl.getPara(ApiBaseController.PARAM_API_KEY_TOKEN);
		Integer userId = ctrl.getParaToInt(ApiBaseController.PARAM_API_KEY_USER_ID);
		
		if (verifyToken(token, userId))
		{
			ai.invoke();
			return;
		}
		
		ctrl.setAttr(AppConst.RESPONSE_KEY_CODE, AppConst.RESPONSE_VALUE_CODE_UNAUTHENTICATION);
		ctrl.setAttr(AppConst.RESPONSE_KEY_MSG, "登录信息已经失效，请重新打开");
		ctrl.renderJson();
	}
	
	

	public boolean verifyToken(String token, Integer userId) 
	{
		if (token == null || token.isEmpty() || userId == null || userId < 0) 
		{
			return false;
		}

		Claims claims = JWTKit.parseJWT(token, JWTKit.APP_BASE64_JWT_SECURITY_KEY);
		
		if (claims == null) 
		{
			return false;
		}
		
		Date expirationTime = claims.getExpiration();
		Calendar cal = Calendar.getInstance();
		Date now = cal.getTime();
		
		return  now.before(expirationTime);
	}
	
}
